package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.LogTypeEnum;
import net.xdclass.model.LogRecord;
import net.xdclass.service.LogService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @description 日志文件测试类
 * @since 2024-01-14 22:03
 */
@Service
@Slf4j
public class LogServiceImpl implements LogService {

    private static final String TOPIC_NAME = "ods_link_visit_topic";

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public JsonData recordShortLinkLog(HttpServletRequest request, String shortLinkCode, Long accountNo) {
        String ip = CommonUtil.getIpAddr(request);
        Map<String, String> headerMap = CommonUtil.getAllRequestHeader(request);
        Map<String, String> availableMap = new HashMap<>();
        availableMap.put("user-agent", headerMap.get("user-agent"));

        availableMap.put("referer", headerMap.get("referer"));

        availableMap.put("accountNo", accountNo.toString());
        LogRecord logRecord = LogRecord.builder()
                //⽇志类型
                .event(LogTypeEnum.SHORT_LINK_TYPE.name())
                //⽇志内容
                .data(availableMap)
                // 客户端ip
                .ip(ip)
                // 时间时间
                .ts(CommonUtil.getCurrentTimestamp())
                // 业务唯⼀id
                .bizId(shortLinkCode).build();
        String jsonLog = JsonUtil.obj2Json(logRecord);
        // 打印控制台
        log.info(jsonLog);
        // 发送kafka
        kafkaTemplate.send(TOPIC_NAME, jsonLog);
        // 存储Mysql 测试数据 TODO
        return JsonData.buildSuccess();
    }

}
